using Avalonia.Controls;
using Avalonia.VisualTree;
using System;
using System.Threading.Tasks;

namespace IntegratedMeasuring.Utils;

/// <summary>
/// 全局加载动画帮助类
/// </summary>
public static class LoadingHelper
{
    /// <summary>
    /// 显示全局加载动画
    /// </summary>
    /// <param name="control">当前控件</param>
    /// <param name="loadingText">加载提示文字</param>
    public static void ShowLoading(Control control, string loadingText = "正在处理中，请稍后...")
    {
        var mainWindow = control.FindAncestorOfType<MainWindow>();
        mainWindow?.ShowGlobalLoading(loadingText);
    }
    
    /// <summary>
    /// 隐藏全局加载动画
    /// </summary>
    /// <param name="control">当前控件</param>
    public static void HideLoading(Control control)
    {
        var mainWindow = control.FindAncestorOfType<MainWindow>();
        mainWindow?.HideGlobalLoading();
    }
    
    /// <summary>
    /// 执行带加载动画的异步操作
    /// </summary>
    /// <param name="control">当前控件</param>
    /// <param name="asyncAction">异步操作</param>
    /// <param name="loadingText">加载提示文字</param>
    public static async Task ExecuteWithLoadingAsync(Control control, Func<Task> asyncAction, string loadingText = "正在处理中，请稍后...")
    {
        ShowLoading(control, loadingText);
        
        try
        {
            await asyncAction();
        }
        finally
        {
            HideLoading(control);
        }
    }
    
    /// <summary>
    /// 执行带加载动画的异步操作并返回结果
    /// </summary>
    /// <typeparam name="T">返回类型</typeparam>
    /// <param name="control">当前控件</param>
    /// <param name="asyncAction">异步操作</param>
    /// <param name="loadingText">加载提示文字</param>
    /// <returns>操作结果</returns>
    public static async Task<T> ExecuteWithLoadingAsync<T>(Control control, Func<Task<T>> asyncAction, string loadingText = "正在处理中，请稍后...")
    {
        ShowLoading(control, loadingText);
        
        try
        {
            return await asyncAction();
        }
        finally
        {
            HideLoading(control);
        }
    }
} 